package com.springboot.helloworld.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @version v1.0
 * @description: 请求切面类
 * @author: xiaoliang.liu
 * @date: 2018/7/1 22:47
 */
@Slf4j
@Aspect
@Component
public class HttpAspect {

    /**
     * 公用切面表达式方法(针对GirlController类)
     */
    @Pointcut(value = "execution(public * com.springboot.helloworld.controller.GirlController.*(..))")
    public void log() {
    }

    /**
     * 在方法执行前的拦截切面(引用前面定义的切入点)
     */
    @Before("log()")
    public void recordLogAtBefore(JoinPoint joinPoint) {
        log.info("http请求切面日志 - 方法执行前");

        // 获得request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // url
        log.info(request.getRequestURL().toString());

        // method
        log.info(request.getMethod());

        // ip
        log.info(request.getRemoteAddr());

        // method-class
        log.info(joinPoint.getSignature().getDeclaringTypeName() + " " + joinPoint.getSignature().getName());

        // args
        log.info("args: {}", joinPoint.getArgs());
    }

    /**
     * 在方法执行后的拦截切面
     */
    @After("log()")
    public void recordLogAtAfter() {
        log.info("http请求切面日志 - 方法执行后");
    }

    /**
     * 获得返回的内容
     *
     * @param object 内容
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void recordLogAtReturning(Object object) {
        log.info(object.toString());
    }
}
